package com.buyhouse.zhaimao.http;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.UUID;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import com.buyhouse.zhaimao.AppConfig;
import com.buyhouse.zhaimao.MyApplication;
import com.buyhouse.zhaimao.util.DebugLog;

/**
 * 网络连接管理类HttpClient/HttpURLConnection
 * 
 * @author zhouby
 *
 */
public class NetManager {

	/**
	 * 最大连接数
	 */
	public final static int MAX_TOTAL_CONNECTIONS = 50;

	/**
	 * 获取连接的最大等待时间
	 */
	public final static int WAIT_TIMEOUT = 10000;

	/**
	 * 每个路由最大连接数
	 */
	public final static int MAX_ROUTE_CONNECTIONS = 50;

	/**
	 * 连接超时时间
	 */
	public final static int CONNECT_TIMEOUT = 30000;

	/**
	 * 读取超时时间
	 */
	public final static int READ_TIMEOUT = 30000;

	/**
	 * 字符编码
	 */
	public final static String CHARSET = "utf-8";

	private static NetManager instance;
	private List<Cookie> cookies;

	/**
	 * 返回实例
	 * 
	 * @return
	 */
	public synchronized static NetManager getInstance() {
		if (instance == null) {
			instance = new NetManager();
		}
		return instance;
	}

	/**
	 * HttpClient 发送get请求
	 * 
	 * @param id
	 *            请求序列id
	 * @param url
	 *            请求url
	 * @param nameValuePairs
	 *            请求参数
	 * @param callback
	 *            回调函数
	 */
	public void sendGetRequest(int id, String url,
			List<BasicNameValuePair> nameValuePairs, HttpCallBack callback) {
		String result = null;

		try {

			HttpGet get = getHttpGet(url + "?" + nameValuePairs);

			if (!url.equals(AppConfig.LOGIN)) {
				get.setHeader("Cookie", getCookie());
			}

			HttpClient client = getHttpClient();

			HttpResponse response = client.execute(get);

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

				if (url.equals(AppConfig.LOGIN)) {
					this.cookies = ((AbstractHttpClient) client)
							.getCookieStore().getCookies();
				}

				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, CHARSET);
					resEntity.consumeContent();
					callback.onSuccess(result, id);
				}
			} else {
				callback.onFailure(null, ""
						+ response.getStatusLine().getStatusCode(), id);
			}

		} catch (Exception e) {
			e.printStackTrace();
			callback.onFailure(e, null, id);
		}

	}

	/**
	 * HttpClient 发送psot请求
	 * 
	 * @param id
	 *            请求序列id
	 * @param url
	 *            请求url
	 * @param nameValuePairs
	 *            请求参数
	 * @param callback
	 *            回调函数
	 */
	public void sendPostRequest(int id, String url,
			List<BasicNameValuePair> nameValuePairs, HttpCallBack callback) {
		String result = null;
		// HttpPost post = getHttpPost(url);
		HttpPost post = new HttpPost(url);

		try {
			post.setEntity(new UrlEncodedFormEntity(nameValuePairs, CHARSET));

			if (!url.equals(AppConfig.LOGIN)) {
				post.setHeader("Cookie", getCookie());
			}

			HttpClient client = getHttpClient();
			HttpResponse response = client.execute(post);

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

				if (url.equals(AppConfig.LOGIN)) {

					this.cookies = ((AbstractHttpClient) client)
							.getCookieStore().getCookies();
				}

				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, CHARSET);
					resEntity.consumeContent();
					callback.onSuccess(result, id);
				}
			} else {
				callback.onFailure(null, response.getStatusLine()
						.getStatusCode() + "", id);
			}
		} catch (Exception e) {
			e.printStackTrace();
			callback.onFailure(e, null, id);
		}

	}

	/**
	 * HttpClient 上传文件（未成功需要调试）
	 * 
	 * @param id
	 *            请求序列id
	 * @param pathToOurFile
	 *            上传文件url
	 * @param url
	 *            请求url
	 * @param callback
	 *            回调函数
	 */
	public void sendPostFile(int id, String pathToOurFile, String url,
			HttpCallBack callback) {
		String result = null;
		// HttpPost post = getHttpPost(url);

		String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
		String CONTENT_TYPE = "multipart/form-data"; // 内容类型
		HttpPost post = new HttpPost(url);

		try {

			if (!url.equals(AppConfig.LOGIN)) {
				post.setHeader("Cookie", getCookie());
			}

			HttpClient client = getHttpClient();

			// HttpClient client=new DefaultHttpClient();

			MultipartEntityBuilder builder = MultipartEntityBuilder.create();

			// builder.setCharset(Charset.forName(HTTP.UTF_8));//设置请求的编码格式
			builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);// 设置浏览器兼容模式

			File file = new File(pathToOurFile);
			FileBody body = new FileBody(file);// 把文件转换成流对象FileBody
			builder.addPart("file", body);
			// builder.addBinaryBody("file", file);
			HttpEntity entity = builder.build();// 生成 HTTP POST 实体

			post.addHeader("User-Agent", MyApplication.getInstance().userAgent);

			post.addHeader("connection", "keep-alive");
			post.addHeader("Content-Type", CONTENT_TYPE + ";boundary="
					+ BOUNDARY);

			post.setEntity(entity);// 设置请求参数

			HttpResponse response = client.execute(post);

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				if (url.equals(AppConfig.LOGIN)) {

					this.cookies = ((AbstractHttpClient) client)
							.getCookieStore().getCookies();
				}

				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, CHARSET);
					resEntity.consumeContent();
					callback.onSuccess(result, id);
				}
			} else {
				callback.onFailure(null, ""
						+ response.getStatusLine().getStatusCode(), id);
			}
		} catch (Exception e) {
			e.printStackTrace();
			callback.onFailure(e, null, id);
		}

	}

	/**
	 * HttpURLConnection 上传文件
	 * 
	 * @param id
	 *            请求序列id
	 * @param pathToOurFile
	 *            上传文件url
	 * @param RequestURL
	 *            请求url
	 * @param callback
	 *            回调函数
	 */
	public void sendLoadFile(int id, String pathToOurFile, String RequestURL,
			HttpCallBack callback) {
		int res = 0;
		String result = null;
		String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
		String PREFIX = "--", LINE_END = "\r\n";
		String CONTENT_TYPE = "multipart/form-data"; // 内容类型

		try {
			URL url = new URL(RequestURL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(CONNECT_TIMEOUT);
			conn.setConnectTimeout(CONNECT_TIMEOUT);
			conn.setDoInput(true); // 允许输入流
			conn.setDoOutput(true); // 允许输出流
			conn.setUseCaches(false); // 不允许使用缓存
			conn.setRequestMethod("POST"); // 请求方式
			conn.setRequestProperty("Charset", CHARSET); // 设置编码
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
					+ BOUNDARY);
			// conn.setRequestProperty("Cookie", cookie);

			if (!url.equals(AppConfig.LOGIN)) {
				conn.setRequestProperty("Cookie", getCookie());
			}

			File file = new File(pathToOurFile);

			if (file != null) {
				/**
				 * 当文件不为空时执行上传
				 */
				DataOutputStream dos = new DataOutputStream(
						conn.getOutputStream());
				StringBuffer sb = new StringBuffer();
				sb.append(PREFIX);
				sb.append(BOUNDARY);
				sb.append(LINE_END);
				sb.append("Content-Disposition: form-data; name=\"path\"")
						.append(LINE_END).append(LINE_END)
						.append("mobile/person/save");
				// sb.append(LINE_END);
				sb.append(LINE_END);

				// dos.write(sb1.toString().getBytes());
				// dos.flush();

				// StringBuffer sb = new StringBuffer();
				sb.append(PREFIX);
				sb.append(BOUNDARY);
				sb.append(LINE_END);
				/**
				 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
				 * filename是文件的名字，包含后缀名
				 */

				sb.append("Content-Disposition: form-data; name=\"file\"; filename=\""
						+ file.getName() + "\"" + LINE_END);
				sb.append("Content-Type: image/jpeg" + LINE_END).append(
						LINE_END);

				dos.write(sb.toString().getBytes());
				InputStream is = new FileInputStream(file);

				long totalSize = is.available();
				long currentSize = 0;

				byte[] bytes = new byte[1024];
				int len = 0;
				while ((len = is.read(bytes)) != -1) {
					dos.write(bytes, 0, len);
					currentSize += len;
					DebugLog.e(
							(int) (currentSize * 100 / (float) totalSize) + "%");
				}
				is.close();
				dos.write(LINE_END.getBytes());
				byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
						.getBytes();
				dos.write(end_data);
				dos.flush();
				/**
				 * 获取响应码 200=成功 当响应成功，获取响应的流
				 */
				res = conn.getResponseCode();
				if (res == 200) {
					InputStream input = conn.getInputStream();
					StringBuffer sb2 = new StringBuffer();
					int ss;
					while ((ss = input.read()) != -1) {
						sb2.append((char) ss);
					}
					result = sb2.toString();
					callback.onSuccess(result, id);
				} else {
					callback.onFailure(null, "" + res, id);
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
			callback.onFailure(e, null, id);
		} catch (IOException e) {
			e.printStackTrace();
			callback.onFailure(e, null, id);
		}
	}

	/**
	 * 获取cookie
	 * 
	 * @return
	 */
	public String getCookie() {
		if (cookies == null) {
			return null;
		}
		StringBuilder sb = new StringBuilder();
		for (Cookie ck : cookies) {
			sb.append(ck.getName()).append('=').append(ck.getValue())
					.append(";");
		}
		return sb.toString();

	}

	/**
	 * 清除cookie
	 * 
	 * @return
	 */
	public void clearCookie() {
		cookies = null;
	}

	/**
	 * HttpClient下载文件
	 * 
	 * @param url
	 *            发送请求url
	 * @return HttpEntity 下载内容
	 */
	public HttpEntity doDownloadFile(String url) {
		HttpEntity httpEntity = null;
		HttpPost post = getHttpPost(url);

		try {
			HttpResponse response = getHttpClient().execute(post);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// response.getEntity().getContent();
				httpEntity = response.getEntity();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return httpEntity;
	}

	/**
	 * 创建一个HttpPost并返回
	 * 
	 * @param url
	 * @return
	 */
	private HttpPost getHttpPost(String url) {
		HttpPost post = new HttpPost(url);
		post.addHeader("Content-Type", "application/json");
		return post;
	}

	/**
	 * 创建一个HttpPost并返回
	 * 
	 * @param url
	 * @return
	 */
	private HttpGet getHttpGet(String url) {
		HttpGet get = new HttpGet(url);
		get.addHeader("Content-Type", "text/html");

		return get;
	}

	/**
	 * 创建一个HttpClient
	 * 
	 * @return
	 */
	private HttpClient getHttpClient() {
		try {
			HttpParams httpParams = new BasicHttpParams();
			// 设置通信协议版本
			httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
					HttpVersion.HTTP_1_1);
			// 设置最大连接数
			ConnManagerParams.setMaxTotalConnections(httpParams,
					MAX_TOTAL_CONNECTIONS);
			// 设置获取连接的最大等待时间
			ConnManagerParams.setTimeout(httpParams, WAIT_TIMEOUT);
			// 设置每个路由最大连接数
			ConnPerRouteBean connPerRoute = new ConnPerRouteBean(
					MAX_ROUTE_CONNECTIONS);
			ConnManagerParams.setMaxConnectionsPerRoute(httpParams,
					connPerRoute);
			// 设置连接超时时间
			HttpConnectionParams.setConnectionTimeout(httpParams,
					CONNECT_TIMEOUT);
			// 设置读取超时时间
			HttpConnectionParams.setSoTimeout(httpParams, READ_TIMEOUT);

			SchemeRegistry registry = new SchemeRegistry();
			registry.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));

			ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(
					httpParams, registry);
			return new DefaultHttpClient(connectionManager, httpParams);
		} catch (Exception e) {
			e.printStackTrace();
			return new DefaultHttpClient();
		}
	}

}
